package com.inspur.edp.common.type.enhanced;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author lizhaorui
 * @date 2025/11/25
 * @description
 */
public class EnhancedServiceLoader {

    private static final Logger LOGGER = LoggerFactory.getLogger(EnhancedServiceLoader.class);

    public static List<Object> loadFile(String fileName, ClassLoader loader) {
        List<Object> objects = new ArrayList<>();
        Enumeration<URL> urls;
        try {
            if (loader != null) {
                urls = loader.getResources(fileName);
            } else {
                urls = ClassLoader.getSystemResources(fileName);
            }
        } catch (IOException ioEx) {
            throw new RuntimeException(String.format("get extension %s occur error", fileName));
        }
        if (urls != null) {
            while (urls.hasMoreElements()) {
                java.net.URL url = urls.nextElement();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        final int ci = line.indexOf('#');
                        if (ci >= 0) {
                            line = line.substring(0, ci);
                        }
                        line = line.trim();
                        if (line.length() > 0) {
                            try {
                                Class loadClass = loader.loadClass(line);
                                Object obj = loadClass.newInstance();
                                objects.add(obj);
                            } catch (LinkageError | ClassNotFoundException e) {
                                LOGGER.warn(String.format("Load [%s] class fail. %s", line, e.getMessage()));
                            } catch (ClassCastException e) {
                                LOGGER.error(String.format("Load [%s] class fail, please make sure the extension" +
                                        " config in %s implements", line, fileName));
                            }
                        }
                    }
                } catch (Throwable e) {
                    LOGGER.warn("load clazz instance error: {}", e.getMessage());
                }
            }
        }
        return objects;
    }

}